<?php

namespace App\Jobs;

use App\Models\Agent;
use App\Models\AgentPromoted;
use App\Models\IndicatorsDailySummary;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;

/**
 * 处理晋升
 * Class PromotionJob
 * @package App\Jobs
 */
class PromotionJob extends Job
{
    public function handle()
    {
        try {
            \DB::beginTransaction();

            $statusUpdate = []; // 状态变更得额外更新,不然会影响 chunk 查询
            AgentPromoted::query()
                ->where('status', AgentPromoted::STATUS_NORMAL)
                ->where('check_date', Carbon::today())
                ->with('agent')
                ->each(function (AgentPromoted $agentPromoted) use (&$statusUpdate) {
                    $status = AgentPromoted::STATUS_PROMOTION_FAILED; // 是否达标
                    /** @var Agent $agent */
                    $agent = $agentPromoted['agent'];
                    $afterVerificationLevel = $agent['level'];

                    $month = Carbon::parse($agentPromoted['created_at'])->format('Ym'); // 以触发条件的当月为准
                    $personalPerformance = $agent->monthlySummary()
                        ->where('month', $month)->where('type', IndicatorsDailySummary::TYPE_AGENT)
                        ->pluck('performance_summary')->first(null, 0); // 当月个人业绩总和
                    $teamPerformance = $agent->monthlySummary()
                        ->where('month', $month)->where('type', IndicatorsDailySummary::TYPE_TEAM)
                        ->pluck('performance_summary')->first(null, 0); // 当月团队业绩总和

                    // 当前什么等级, 个人业绩, 以及团队业绩 (是否达标)
                    if ((int) $agent['level'] === Agent::LEVEL_GROUP_OWNER) {
                        // 先校验是否达到 精英
                        if ($personalPerformance >= Agent::LEVEL_MAP[Agent::LEVEL_GROUP_OWNER]['employment']['self']
                            && ($personalPerformance + $teamPerformance) >= Agent::LEVEL_MAP[Agent::LEVEL_GROUP_OWNER]['employment']['team']) {

                            $status = AgentPromoted::STATUS_PROMOTED;
                            $afterVerificationLevel = Agent::LEVEL_ELITE;
                        }
                        // 是否达到大咖
                        if ($personalPerformance >= Agent::LEVEL_MAP[Agent::LEVEL_ELITE]['employment']['self']
                            && ($personalPerformance + $teamPerformance) >= Agent::LEVEL_MAP[Agent::LEVEL_ELITE]['employment']['team']) {

                            $status = AgentPromoted::STATUS_PROMOTED;
                            $afterVerificationLevel = Agent::LEVEL_STRONGMAN;
                        }
                    } elseif ((int) $agent['level'] === Agent::LEVEL_ELITE) {
                        // 是否达到大咖
                        if ($personalPerformance >= Agent::LEVEL_MAP[Agent::LEVEL_ELITE]['employment']['self']
                            && ($personalPerformance + $teamPerformance) >= Agent::LEVEL_MAP[Agent::LEVEL_ELITE]['employment']['team']) {

                            $status = AgentPromoted::STATUS_PROMOTED;
                            $afterVerificationLevel = Agent::LEVEL_STRONGMAN;
                        }
                    } elseif ((int) $agent['level'] === Agent::LEVEL_STRONGMAN) { // 已经是大咖了, 直接通过
                        $status = AgentPromoted::STATUS_PROMOTED;
                        $afterVerificationLevel = Agent::LEVEL_STRONGMAN;
                    }

                    // 用户等级有变更
                    if ($afterVerificationLevel !== (int) $agent['level']) {
                        $agent->update(['level' => $afterVerificationLevel]);
                    }

                    $statusUpdate[$agentPromoted['id']] = [
                        'status' => $status,
                        'after_verification_level' => $afterVerificationLevel,
                        'when_verifying_personal_performance' => $personalPerformance,
                        'when_verifying_team_performance' => $teamPerformance,
                        'direct_inviter' => $agent['direct_inviter'],
                        'indirect_inviter' => $agent['indirect_inviter'],
                        'affiliated_partner' => $agent['affiliated_partner'],
                    ];
                });

            // 这里得分开更新, 不然上面 each 查询会有问题
            foreach ($statusUpdate as $id => $updateValue) {
                AgentPromoted::query()->where('id', $id)->update($updateValue);
            }

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error('晋升处理发生错误: ' . $e->getMessage());

            throw $e;
        }
    }
}
